package com.qf.oa_system.controller;

import com.qf.oa_system.entity.*;
import com.qf.oa_system.service.*;
import com.qf.oa_system.util.FtpFileUpload;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * ????????Ա(Admin)表控制层
 *
 * @author makejava
 * @since 2020-06-03 20:26:18
 */
@EnableAutoConfiguration
@Controller
@RequestMapping("admin")
public class AdminController {
    /**
     * 服务对象
     */
    @Resource
    private AdminService adminService;

    @Resource
    private ClassesService classesService;

    @Resource
    private RolesService rolesService;

    @Resource
    private UserService userService;

    @Resource
    private CourseService courseService;

    @Resource
    private TeacherService teacherService;

    @Resource
    private UserRolesService userRolesService;

    @Resource
    private StudentService studentService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Admin selectOne(Integer id) {
        return this.adminService.queryById(id);
    }

    @RequestMapping("classUI")
    public String classUI(Model model){
        List<Classes> classes = classesService.queryAll();
        model.addAttribute("classes",classes);
        return "adminclass";
    }

    @RequestMapping("deleteclass")
    public String deleteclasses(int classId,Model model){
        List<Student> students = studentService.queryAllByClassId(classId);
        if(students.size() == 0){
            classesService.deleteById(classId);
        }else {
            model.addAttribute("msg","班级内有学生，无法删除，请修改学生班级之后在进行删除。");
            return classUI(model);
        }

        return "redirect:classUI";
    }

    @RequestMapping("classAddUI")
    public String classAddUI(){
        return "adminclassadd";
    }

    @RequestMapping("classAdd")
    public String classAdd(String className){
        Classes classes = new Classes();
        classes.setClassName(className);
        classesService.insert(classes);
        return "redirect:classUI";
    }

    @RequestMapping("updateClassUI")
    public String classupdateUI(Model model,int classId){
        Classes classes = classesService.queryById(classId);
        model.addAttribute("classes",classes);
        return "adminclassupdate";
    }

    @RequestMapping("classUpdate")
    public String classupdate(Classes classes){
        classesService.update(classes);
        return "redirect:classUI";
    }

    @RequestMapping("rolesUI")
    public String rolesUI(Model model){
        List<Roles> roles = rolesService.queryAll();
        model.addAttribute("roles",roles);
        return "adminroles";
    }

    @RequestMapping("rolesAddUI")
    public String rolesAddUI(){
        return "adminrolesadd";
    }

    @RequestMapping("rolesAdd")
    public String rolesAdd(String roleName){
        Roles roles = new Roles();
        roles.setRoleName(roleName);
        rolesService.insert(roles);
        return "redirect:rolesUI";
    }

    @RequestMapping("deleteroles")
    public String deleteroles(int roleId,Model model){

        List<UserRoles> userRoles = userRolesService.queryByRolesId(roleId);
        if (userRoles.size() == 0){
            rolesService.deleteById(roleId);
        }else {
            model.addAttribute("msg","角色内有用户，无法删除，请修改用户角色之后在进行删除。");
            return rolesUI(model);
        }
        return "redirect:rolesUI";
    }

    @RequestMapping("updateRolesUI")
    public String rolesupdateUI(Model model,int roleId){
        Roles roles = rolesService.queryById(roleId);
        model.addAttribute("roles",roles);
        return "adminrolesupdate";
    }

    @RequestMapping("rolesUpdate")
    public String rolesupdate(Roles roles){
        rolesService.update(roles);
        return "redirect:rolesUI";
    }

    @RequestMapping("updatePasswordUI")
    public String updatepasswordUI(Model model, HttpSession session){
        User user = (User)session.getAttribute("user");
        model.addAttribute("user",user);
        return "updatepassword";
    }

    @RequestMapping("updatePassword")
    public String updatepassword(User user){
        String password=user.getUserPassword();
        //如果在修改的时候没有设置密码，就表示不改动密码
        if(user.getUserPassword().length()!=0) {
            String salt = new SecureRandomNumberGenerator().nextBytes().toString();
            int times = 2;
            String algorithmName = "md5";
            String encodedPassword = new SimpleHash(algorithmName,password,salt,times).toString();
            user.setSalt(salt);
            user.setUserPassword(encodedPassword);
        }
        else{
            user.setUserPassword(null);
        }
        userService.update(user);

        return "redirect:/user/loginpage";
    }

    @RequestMapping("courseUI")
    public String courseUI(Model model){
        List<Course> courses = courseService.queryAll();
        model.addAttribute("courses",courses);
        return "admincourse";
    }

    @RequestMapping("courseAddUI")
    public String courseAddUI(){
        return "admincourseadd";
    }

    @RequestMapping("courseAdd")
    public String courseAdd(String couName){
        Course course = new Course();
        course.setCouName(couName);
        courseService.insert(course);
        return "redirect:courseUI";
    }

    @RequestMapping("deletecourse")
    public String deletecourse(int couId,Model model){
        List<Teacher> teachers = teacherService.getTeaByCourseId(couId);
        if (teachers.size() == 0){
            courseService.deleteById(couId);
        }else {
            model.addAttribute("msg","课程内有老师，无法删除，请修改老师课程之后在进行删除。");
            return courseUI(model);
        }
        return "redirect:courseUI";
    }

    @RequestMapping("updateCourseUI")
    public String courseupdateUI(Model model,int couId){
        Course course = courseService.queryById(couId);
        model.addAttribute("course",course);
        return "admincourseupdate";
    }

    @RequestMapping("courseUpdate")
    public String courseupdate(Course course){
        courseService.update(course);
        return "redirect:courseUI";
    }

    @RequestMapping("userUI")
    public String userUI(Model model){
        List<User> users = userService.queryAll();
        model.addAttribute("users",users);
        return "adminuser";
    }

    @RequestMapping("userAddUI")
    public String useraddUI(Model model){
        List<Roles> roles1 = rolesService.queryAll();
        model.addAttribute("roles",roles1);
        return "adminuseradd";
    }

    @RequestMapping("userAdd")
    public String useradd(User user,String roleName){
        String password = user.getUserPassword();
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        int times = 2;
        String algorithmName = "md5";
        String encodedPassword = new SimpleHash(algorithmName,password,salt,times).toString();
        user.setSalt(salt);
        user.setUserPassword(encodedPassword);
        userService.insert(user);
        User user1 = userService.queryByName(user.getUserName());
        Roles role = rolesService.queryByName(roleName);
        UserRoles userRoles = new UserRoles();
        userRoles.setRoleId(role.getRoleId());
        userRoles.setUserId(user1.getUserId());
        userRolesService.insert(userRoles);
        return "redirect:userUI";
    }
    @RequestMapping("deleteuser")
    public String deleteuser(int userId){
        userService.deleteById(userId);
        userRolesService.deleteById(userId);
        return "redirect:userUI";
    }

    @RequestMapping("updateUserUI")
    public String userupdateUI(Model model,int userId){
        User user = userService.queryById(userId);
        UserRoles userRoles = userRolesService.queryById(userId);
        Roles roles = rolesService.queryById(userRoles.getRoleId());
        List<Roles> roles1 = rolesService.queryAll();
        user.setRoles(roles);
        model.addAttribute("roles",roles1);
        model.addAttribute("users",user);
        return "adminuserupdate";
    }

    @RequestMapping("userUpdate")
    public String userupdate(User user,String roleName){
        String password = user.getUserPassword();
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        int times = 2;
        String algorithmName = "md5";
        String encodedPassword = new SimpleHash(algorithmName,password,salt,times).toString();
        user.setSalt(salt);
        user.setUserPassword(encodedPassword);
        userService.update(user);
        Roles roles = rolesService.queryByName(roleName);
        userRolesService.update(new UserRoles(user.getUserId(),roles.getRoleId()));
        return "redirect:userUI";
    }

    @PostMapping(value = "/updateImg")
    public String fileUpload(@RequestParam(value = "imgFile") MultipartFile file, HttpSession session) throws IOException {
//        if (file.isEmpty()) {
//            System.out.println("文件为空空");
//        }
        String fileName1 = file.getOriginalFilename();
//        System.out.println(fileName1);
        User user = (User)session.getAttribute("user");
//        String fileName = user.getUserName();
        String suffixName = fileName1.substring(fileName1.lastIndexOf("."));  // 后缀名
//        String filePath = ClassUtils.getDefaultClassLoader().getResource("static/img/headimg").getPath();
//        filePath = filePath.substring(1);
//        fileName = fileName + suffixName; // 新文件名
//        System.out.println(filePath+"="+fileName);
//        File dest = new File(filePath + "/"+fileName);
//        if (!dest.getParentFile().exists()) {
//            dest.getParentFile().mkdirs();
//        }
//        try {
//            file.transferTo(dest);
//            System.out.println("上传成功");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        String fileName = UUID.randomUUID().toString() + suffixName;
        FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
        FtpFileUpload.uploadHeadPic(fileName,fileInputStream);
//        String filename = "/img/headimg/" + fileName;
        String addr ="http://39.97.124.153/images/" + fileName;
        System.out.println(addr);
        userService.setimg(addr,user.getUserId());
        session.setAttribute("filename",addr);
        return "index";
    }

}